package com.guigu.work.controller;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.base.entity.CoreOrg;
import com.guigu.base.entity.GlobalUser;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import com.guigu.work.dto.TaskPickupDispatchDTO;
import com.guigu.work.entity.TaskPickupDispatch;
import com.guigu.work.feign.BaseFeign;
import com.guigu.work.feign.OrderFeign;
import com.guigu.work.service.TaskPickupDispatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 取件、派件任务信息表 前端控制器
 * </p>
 *
 * @author liAo
 * @since 2021-11-09
 */
@Slf4j
@Api(tags = "取件、派件任务信息操作接口")
@RestController
@RequestMapping("/task-pickup-dispatch")
public class TaskPickupDispatchController {

    private TaskPickupDispatchService service;
    private BaseFeign baseFeign;

    public TaskPickupDispatchController(TaskPickupDispatchService service, BaseFeign baseFeign) {
        this.service = service;
        this.baseFeign = baseFeign;
    }
    @Autowired
    private OrderFeign orderFeign;

    /**
     * 新增取派件任务
     *
     * @param dto 取派件任务信息
     * @return 存储结果
     */
    @ApiOperation(value = "新增取派件任务", notes = "基本属性无ID")
    @PostMapping("/save")
    public R save(@RequestBody TaskPickupDispatchDTO dto) {
        TaskPickupDispatch dispatch = service.saveTaskPickupDispatch(dto);

        return new R(ResultCode.SUCCESS_CODE, "取派件任务添加成功!", true, dispatch);
    }

    /**
     * 修改取派件任务信息
     *
     * @param dto 取派件任务信息
     * @return 取派件任务信息
     */
    @ApiOperation(value = "修改取派件任务信息", notes = "基本属性有ID")
    @PutMapping("/")
    public R updateById(@RequestBody TaskPickupDispatchDTO dto) {

        TaskPickupDispatch dispatch = service.updateMsgById(dto);

        return new R(ResultCode.SUCCESS_CODE, "取派件任务修改成功!", true, dispatch);
    }

    /**
     * 修改订单状态
     *
     * @param id 编号
     * @param status 状态
     * @return 取派件任务信息
     */
    @ApiOperation(value = "修改取派件任务信息",notes = "基本属性有ID")
    @GetMapping("/updateStatusById/{id}/{status}/{orderId}/{orderStatus}")
    public R updateStatusById(@PathVariable("id") String id,
                              @PathVariable("status") Integer status,
                              @PathVariable("orderId") String orderId,
                              @PathVariable("orderStatus") Integer orderStatus) {
        TaskPickupDispatch dispatch=new TaskPickupDispatch();
        dispatch.setId(id);
        dispatch.setStatus(status);
        if(status == 4 || status ==8){
            dispatch.setActualEndTime(new Date());
        }
        orderFeign.updateStatusById(orderId,orderStatus);
        boolean  b= service.updateById(dispatch);

        return new R(ResultCode.SUCCESS_CODE,"取派件任务状态修改成功!",b);
    }

    /**
     * 获取取派件任务分页数据
     *
     * @param dto 查询条件
     * @return 取派件分页数据
     */
    @ApiOperation(value = "获取取派件任务分页数据", notes = "paged&pageSize&taskType&courierId&assignedStatus&status")
    @PostMapping("/page")
    public R<IPage<TaskPickupDispatchDTO>> findByPage(@RequestBody TaskPickupDispatchDTO dto) {
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(10);
        }
        IPage<TaskPickupDispatch> orderIPage = service.findByPage(dto);

        List<TaskPickupDispatchDTO> list = orderIPage.getRecords().stream().map(t -> {
            TaskPickupDispatchDTO d = new TaskPickupDispatchDTO();

            BeanUtils.copyProperties(t, d);
            if (StringUtils.isNotBlank(t.getAgencyId())) {
                CoreOrg coreOrg = baseFeign.findCoreOrgById(t.getAgencyId()).getData();
                if (ObjectUtils.isNotEmpty(coreOrg)) {
                    d.setAgencyName(coreOrg.getName());
                }
            }
            if (StringUtils.isNotBlank(t.getCourierId())) {
                GlobalUser user = baseFeign.queryAccordingToTheCourierId(t.getCourierId());
                if (ObjectUtils.isNotEmpty(user)) {
                    d.setCourierName(user.getName());
                }
            }
            return d;
        }).collect(Collectors.toList());

        IPage<TaskPickupDispatchDTO> pickupDispatchDTOIpage = new Page<>();
        pickupDispatchDTOIpage.setRecords(list);
        pickupDispatchDTOIpage.setPages(orderIPage.getPages());
        pickupDispatchDTOIpage.setTotal(orderIPage.getTotal());
        pickupDispatchDTOIpage.setCurrent(orderIPage.getCurrent());
        pickupDispatchDTOIpage.setSize(orderIPage.getSize());
        log.info("orderIPage查询数据:" + orderIPage.getTotal());
        return new R<IPage<TaskPickupDispatchDTO>>(ResultCode.SUCCESS_CODE, "取派件任务查询成功!", true, pickupDispatchDTOIpage);
    }

    /**
     * 获取 取派件任务列表
     *
     * @param dto 查询条件
     * @return 取派件任务列表
     */
    @ApiOperation(value = "获取取派件任务数据", notes = "ids&orderIds&taskType&courierId&assignedStatus&status")
    @PostMapping("/list")
    public R<TaskPickupDispatch> findAll(@RequestBody TaskPickupDispatchDTO dto) {
        List<TaskPickupDispatch> dispatchList = this.service.findAll(dto);

        return new R(ResultCode.SUCCESS_CODE,"取派件任务查询成功!",true,dispatchList) ;
    }

    /**
     * 获取 取件任务列表
     *
     * @param courierId 查询条件
     * @return 取派件任务列表
     */
    @ApiOperation(value = "根据快递员ID获取取派件任务数据",notes = "ids&orderIds&taskType&courierId&assignedStatus&status")
    @GetMapping("/list/pickup/{courierId}/{status}")
    public R findByCourierId(@PathVariable("courierId") String courierId,@PathVariable("status") Integer status) {
        Map<String, Object> map = new HashMap<>();
        //待上门
        List<Object> pickup1 = new ArrayList<>();
        //需交件
        List<Object> pickup3 = new ArrayList<>();
        //已完成
        List<Object> pickup4 = new ArrayList<>();
        //已取消
        List<Object> pickup5 = new ArrayList<>();
        TaskPickupDispatchDTO dto=new TaskPickupDispatchDTO();
        dto.setCourierId(courierId);
        //取件任务
        dto.setTaskType(status);
        List<TaskPickupDispatch> dispatchList = this.service.findAll(dto);
        map.put("all",dispatchList);
        if(CollUtil.isNotEmpty(dispatchList)){

            for(TaskPickupDispatch pd: dispatchList) {
                R<Map> orderR = orderFeign.getOrderInfoByOrderId(pd.getOrderId());
                if (pd.getStatus() == 1) {
                    pickup1.add(orderR.getData());
                    continue;
                } else if (pd.getStatus() == 3) {
                    pickup3.add(orderR.getData());
                    continue;
                } else if (pd.getStatus() == 4) {
                    pickup4.add(orderR.getData());
                    continue;
                } else if (pd.getStatus() == 5) {
                    pickup5.add(orderR.getData());
                    continue;
                }

            }
        }
        map.put("pickup1",pickup1);
        map.put("pickup3",pickup3);
        map.put("pickup4",pickup4);
        map.put("pickup5",pickup5);
        return new R(ResultCode.SUCCESS_CODE,"取件任务查询成功!",true,map) ;
    }

    /**
     * 根据id获取取派件任务信息
     *
     * @param id 任务Id
     * @return 任务详情
     */
    @ApiOperation(value = "根据id获取取派件任务信息", notes = "id")
    @GetMapping("/{id}")
    public R<TaskPickupDispatch> findById(@PathVariable(name = "id") String id) {
        TaskPickupDispatchDTO dto = new TaskPickupDispatchDTO();
        TaskPickupDispatch dispatch = service.findById(id);

        return new R<TaskPickupDispatch>(ResultCode.SUCCESS_CODE, "根据id获取取派件任务信息成功!", true, dispatch);
    }

    /**
     * 根据订单id获取取派件任务信息
     *
     * @param orderId 订单Id
     * @return 任务详情
     */
    @ApiOperation(value = "根据订单id获取取派件任务信息", notes = "订单ID&任务类型-1取件任务|2-派件任务")
    @GetMapping("/orderId/{orderId}/{taskType}")
    public R<TaskPickupDispatch> findByOrderId(@PathVariable("orderId") String orderId, @PathVariable("taskType") Integer taskType) {
        TaskPickupDispatch dispatch = this.service.findByOrderId(orderId, taskType);
        return new R<TaskPickupDispatch>
                (ResultCode.SUCCESS_CODE, "根据订单id获取取派件任务信息成功!", true, dispatch);
    }

    /**
     * 根据机构Id查询它对应的快递员信息
     *
     * @param coreOrgId 机构Id
     * @return
     */
    @ApiOperation("根据机构Id查询它对应的快递员信息")
    @GetMapping("/findGlobalUserByCoreOrgId/{coreOrgId}")
    public R<List<GlobalUser>> findGlobalUserByCoreOrgId(@PathVariable("coreOrgId") String coreOrgId) {
        R<List<GlobalUser>> r = baseFeign.findGlobalUserByCoreOrgId(coreOrgId);
        return r;
    }

    /**
     * 人工分配快递员
     *
     * @param taskPickUpDispatchId 取派件任务Id
     * @param courierId            快递员Id
     * @return
     */
    @ApiOperation("人工分配快递员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskPickUpDispatchId", value = "取派件任务"),
            @ApiImplicitParam(name = "courierId", value = "快递员Id(用户Id)")
    })
    @PutMapping("/courierAssignment/{taskPickUpDispatchId}/{courierId}")
    public R courierAssignment(@PathVariable String taskPickUpDispatchId,
                               @PathVariable String courierId) {
        TaskPickupDispatch t = new TaskPickupDispatch();
        t.setId(taskPickUpDispatchId);
        t.setCourierId(courierId);
        t.setAssignedStatus(2);
        service.updateById(t);
        return new R(ResultCode.SUCCESS_CODE, "人工分配快递员成功!", true);
    }


    /**
     * 批量添加取派件任务
     *
     * @param list 对象集合
     * @return
     */
    @PostMapping("/addTaskPickupDispatch")
    @ApiOperation("批量添加取派件任务")
    @ApiImplicitParam(name = "list", value = "取派件对象集合")
    public R addTaskPickupDispatch(@RequestBody List<TaskPickupDispatchDTO> list) {
        List<TaskPickupDispatch> taskPickupDispatches = list.stream().map(t -> {
            TaskPickupDispatch taskPickupDispatch = new TaskPickupDispatch();
            BeanUtils.copyProperties(t, taskPickupDispatch);
            /**
             * 设置预计开始时间
             */
            taskPickupDispatch.setEstimatedStartTime(new Date());
            /**
             * 设置实际开始时间
             */
            taskPickupDispatch.setActualStartTime(new Date());
            /**
             * 设置创建时间
             */
            taskPickupDispatch.setCreateTime(new Date());
            return taskPickupDispatch;
        }).collect(Collectors.toList());

        /**
         * 判断该订单之前是否已经添加到取派件任务表中
         */
        List<TaskPickupDispatch> pickupDispatches = taskPickupDispatches.stream().filter(t -> {
            QueryWrapper<TaskPickupDispatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", t.getOrderId());
            TaskPickupDispatch one = this.service.getOne(queryWrapper);
            if (ObjectUtils.isNotEmpty(one)) {
                /**
                 *在订单唯一情况下删除之前的取派件信息
                 */
                this.service.remove(queryWrapper);
            }
            return true;
        }).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(pickupDispatches)) {
            /***
             * 批量添加
             */
            service.saveOrUpdateBatch(pickupDispatches);
        }
        return new R(ResultCode.SUCCESS_CODE, "新增快递员取派件任务成功!");
    }
}

